﻿/**
 * opencti softphone.js
 */
var VOICE_STATUS_UNKNOWN = "Unknown";
var VOICE_STATUS_DIALING = "Dialing";
var VOICE_STATUS_TALKING = "Established";
var VOICE_STATUS_RINGING = "Ringing";
var VOICE_STATUS_HELD = "Held";
var VOICE_STATUS_IDLE = "Idle";
var path = "";
var _sessionId = "";
var url = "";
var connId = "";
var transferConnId="";
var serverUrl = "10.128.64.70:8090";
// 拨打电话地址
var callUrl = "http://"+serverUrl+"/api/v1/me/calls/";
// 初始化channel地址
var initChannelUrl = "http://"+serverUrl+"/api/v1/me/channel/";
// 初始化所有channel
var initAllChannelUrl = "http://"+serverUrl+"/api/v1/me/channels/";
var heartbeatUrl="http://"+serverUrl+"/api/v1/me/heart";
var connId_chat = "";




//
function login1() {
	Online("voice");
}

function logout1() {

	offLine("voice");
}

function ready1() {
	ready("voice");
}

function notReady1() {
	notReady("voice");
}

function answerCall1() {
	answerCall(connId);
}

function releaseCall1() {
	if(transferConnId!=""){
		hangup(transferConnId);
	}else{
	    hangup(connId);
	}

}

function makeCall1(phoneNumber) {
	var params = "{\"v_calltype\":\"3\"}";
	dialCall(phoneNumber, params);
}

function holdCall1() {
	if(transferConnId!=""){
		holdCall(transferConnId);
	}else{
	    holdCall(connId);
	}
}

function retrieveCall1() {
	if(transferConnId!=""){
		retrieveCall(transferConnId);
	}else{
	   retrieveCall(connId);
	}
}

function initiateTransfer1(phoneNumber) {
	initiateTransfer(phoneNumber, connId);
}

/**
 * 完成转接
 * @return
 */
function completeTransfer1() {
	completeTransfer(connId,transferConnId);
}
/**
 * initiateConference1 会议（第一步）
 * @return
 */
function initiateConference1(phoneNumber) {
	var userData = "{\"a\":\"1\",\"b\":\"2\"}";
	initiateConference(phoneNumber, connId,userData);
}

/**
 * completeConference1 完成会议
 * @return
 */
function completeConference1() {
	completeConference(connId,transferConnId);
}

/**
 * 单步会议
 * @return
 */
function singleStepConference1(phoneNumber){
	var userData = "{\"a\":\"1\",\"b\":\"2\"}";
	singleStepConference(phoneNumber, connId, userData)
}



/**
 * 软电话状态改变
 * @param state
 * @return
 */
function showButtons(state) {
	log("state is:"+state);
	flag = state;
	switch (state) {

	case 2://签入
		$("#btnLogout").removeClass("disable");
		$("#btnReady").removeClass("disable");
		$("#btnLogin").addClass("disable");
		//$("#btnCall").attr("src", imagePrefix+"images/btns-k-answer.png");
        $(".dian_tu").removeClass("disable");
        $(".caoZ_s").removeClass("disable");
        $("#btnCall").removeClass("disable");
		$("#phoneNo").removeAttr("disabled","disabled");
		$("#answer").attr("src", imagePrefix+"huiDian.png");
		$("#refuse").attr("src", imagePrefix+"huiDian.png");
        $("#refuse").addClass("disable");
        $("#answer").addClass("disable");
		$("#btnTransfer").addClass("disable");
		$("#btnConference").addClass("disable");
		$("#btnConsult").addClass("disable");
		$("#btnToSatis").addClass("disable");
		$("#validatePwd").addClass("disable");
		break;
	case 3:// 就绪
		$("#btnNotReady").removeClass("disable");
		$("#btnReady").addClass("disable");
		if($("#refuse").attr("src").indexOf("disable") > -1) {//没有电话
			//$("#btnCall").attr("src", imagePrefix+"images/btns-k-answer.png");
            $(".dian_tu").removeClass("disable");
            $(".caoZ_s").removeClass("disable");
            $("#btnCall").removeClass("disable");
			$("#answer").attr("src", imagePrefix+"huiDian.png");
			$("#refuse").attr("src", imagePrefix+"huiDian.png");
            $("#refuse").addClass("disable");
            $("#answer").addClass("disable");
			$("#phoneNo").removeAttr("disabled","disabled");
			$("#btnTransfer").addClass("disable");
			$("#btnConference").addClass("disable");
			$("#btnConsult").addClass("disable");
			$("#btnToSatis").addClass("disable");
			$("#validatePwd").addClass("disable");
		}else{//有电话


		}

		break;
	case 4://未就绪
		$("#btnNotReady").addClass("disable");
		$("#btnReady").removeClass("disable");
		$("#phoneNo").removeAttr("disabled");
		break;
	case 6://签出
		$("#btnLogout").addClass("disable");
		$("#btnLogin").removeClass("disable");
		$("#btnReady").addClass("disable");
		$("#btnNotReady").addClass("disable");
        //$("#btnCall").attr("src", imagePrefix+"images/btns-k-answer-disabled.png");
        $(".dian_tu").addClass("disable");
        $(".caoZ_s").addClass("disable");
        $("#btnCall").addClass("disable");
        
		$("#phoneNo").attr("disabled","disabled");
		$("#answer").attr("src", imagePrefix+"huiDian.png");
		$("#refuse").attr("src", imagePrefix+"huiDian.png");
        $("#refuse").addClass("disable");
        $("#answer").addClass("disable");
		$("#btnTransfer").addClass("disable");
		$("#btnConference").addClass("disable");
		$("#btnConsult").addClass("disable");
		$("#btnToSatis").addClass("disable");
		$("#validatePwd").addClass("disable");
		break;
	case 7://呼出

		$("#refuse").attr("src", imagePrefix+"dianHo.png");
		$("#phoneNo").attr("disabled","disabled");
		$("#answer").attr("src", imagePrefix+"huiDian.png");
        $("#answer").addClass("disable");
        $("#refuse").removeClass("disable");

		//$("#btnCall").attr("src", imagePrefix+"images/btns-k-answer-disabled.png");
        $(".dian_tu").addClass("disable");
        $(".caoZ_s").addClass("disable");
        $("#btnCall").addClass("disable");
        $("#call").attr("src", imagePrefix+"dianDon.gif");
        
		$("#btnTransfer").addClass("disable");
		$("#btnConference").addClass("disable");
		$("#btnConsult").addClass("disable");
		$("#btnToSatis").addClass("disable");
		$("#validatePwd").addClass("disable");
		break;
	case 8://进线
		$("#refuse").attr("src", imagePrefix+"dianHo.png");
		$("#answer").attr("src", imagePrefix+"dianLu.png");
        $("#refuse").removeClass("disable");
        $("#answer").removeClass("disable");
		//$("#btnCall").attr("src", imagePrefix+"images/btns-k-answer-disabled.png");
        $(".dian_tu").addClass("disable");
        $(".caoZ_s").addClass("disable");
        $("#btnCall").addClass("disable");
        $("#call").attr("src", imagePrefix+"dianDon.gif");
		$("#phoneNo").attr("disabled","disabled");
		$("#btnTransfer").addClass("disable");
		$("#btnConference").addClass("disable");
		$("#btnConsult").addClass("disable");
		$("#btnToSatis").addClass("disable");
		$("#validatePwd").addClass("disable");
		break;
	case 9://应答
		$("#answer").attr("src", imagePrefix+"huiDian.png");
		$("#refuse").attr("src", imagePrefix+"dianHo.png");
        $("#refuse").removeClass("disable");
        $("#answer").addClass("disable");
        $("#call").attr("src", imagePrefix+"dianDon.gif");
		//$("#btnCall").attr("src", imagePrefix+"images/btns-k-answer.png");
        $(".dian_tu").removeClass("disable");
        $(".caoZ_s").removeClass("disable");
        $("#btnCall").removeClass("disable");
		$("#btnToSatis").removeClass("disable");
		$("#phoneNo").removeAttr("disabled");
		$("#btnTransfer").removeClass("disable");
		$("#btnConference").removeClass("disable");
		$("#btnTransfer").addClass("transfer");
		$("#btnConference").addClass("conference");
		$("#btnToSatis").removeClass("disable");
		$("#validatePwd").removeClass("disable");
		$("#btnTransfer").html("咨询转接");
		$("#btnConference").html("咨询会议");

	break;
	case 10://保持
			$("#btnHold").attr("src", imagePrefix+"images/btns-sound.png");
			$("#btnHold").removeClass("hold");

		break;
	case 11://取回
		$("#btnHold").attr("src", imagePrefix+"images/btns-hold.png");
		$("#btnHold").addClass("hold");
		break;
	case 13://通话挂断
		$("#refuse").attr("src", imagePrefix+"huiDian.png");
		$("#answer").attr("src", imagePrefix+"huiDian.png");
        $("#refuse").addClass("disable");
        $("#answer").addClass("disable");
        $("#call").attr("src", imagePrefix+"yiS.png");
        $("#phoneNumber").html("");
		//$("#btnCall").attr("src", imagePrefix+"images/btns-k-answer.png");
        $(".dian_tu").removeClass("disable");
        $(".caoZ_s").removeClass("disable");
        $("#btnCall").removeClass("disable");
		
		$("#phoneNo").removeAttr("disabled");
		$("#btnTransfer").addClass("disable");
		$("#btnConference").addClass("disable");
		$("#btnConsult").addClass("disable");
		$("#btnToSatis").addClass("disable");
		$("#validatePwd").addClass("disable");
		$("#btnTransfer").html("咨询转接");
		$("#btnConference").html("咨询会议");
		$("#phoneNumber").val("");
		break;
	case 14://咨询 只显示挂断，转接完成，会议完成按钮
		$("#answer").attr("src", imagePrefix+"huiDian.png");
		$("#refuse").attr("src", imagePrefix+"dianHo.png");
        $("#refuse").removeClass("disable");
        $("#answer").addClass("disable");
		//$("#btnCall").attr("src", imagePrefix+"images/btns-k-answer-disabled.png");
		$("#phoneNo").attr("disabled","disabled");
		$("#btnTransfer").addClass("disable");
		$("#btnConference").addClass("disable");
		$("#btnConsult").addClass("disable");
		$("#btnToSatis").addClass("disable");
		$("#validatePwd").addClass("disable");
		break;
	case 17://咨询应答中  只有保持和挂断
		$("#answer").attr("src", imagePrefix+"huiDian.png");
		$("#refuse").attr("src", imagePrefix+"dianHo.png");
		//$("#btnCall").attr("src", imagePrefix+"images/btns-k-answer-disabled.png");
		$("#phoneNo").attr("disabled","disabled");
		$("#btnTransfer").addClass("disable");
		$("#btnConference").addClass("disable");
		$("#btnToSatis").addClass("disable");
		$("#validatePwd").addClass("disable");
		$("#btnTransfer").html("咨询转接");
		$("#btnConference").html("咨询会议");
		break;
	case 18://咨询会议应答中  只有保持和挂断，会议完成按钮
		$("#answer").attr("src", imagePrefix+"huiDian.png");
		$("#refuse").attr("src", imagePrefix+"dianHo.png");
		//$("#btnCall").attr("src", imagePrefix+"images/btns-k-answer-disabled.png");
		$("#phoneNo").attr("disabled","disabled")
		$("#btnConference").removeClass("disable");
		$("#btnToSatis").addClass("disable");
		$("#validatePwd").addClass("disable");
		$("#btnConference").removeClass("conference");
		$("#btnConference").html("会议完成");

		break;
	case 19://会议应答
		$("#answer").attr("src", imagePrefix+"huiDian.png");
		$("#refuse").attr("src", imagePrefix+"dianHo.png");
		//$("#btnCall").attr("src", imagePrefix+"images/btns-k-answer-disabled.png");
		$("#phoneNo").attr("disabled","disabled");
		$("#btnTransfer").addClass("disable");
		$("#btnConference").addClass("disable");
		$("#btnConsult").addClass("disable");
		$("#btnToSatis").addClass("disable");
		$("#validatePwd").addClass("disable");
		break;
	case 20://咨询转接应答中  只有保持和挂断，转接完成按钮
		$("#answer").attr("src", imagePrefix+"huiDian.png");
		$("#refuse").attr("src", imagePrefix+"dianHo.png");
		//$("#btnCall").attr("src", imagePrefix+"images/btns-k-answer-disabled.png");
		$("#phoneNo").attr("disabled","disabled")
		$("#btnTransfer").removeClass("disable");
		$("#btnToSatis").addClass("disable");
		$("#validatePwd").addClass("disable");
		$("#btnTransfer").removeClass("transfer");
		$("#btnTransfer").html("转接完成");
		break;
}
}

// ---------------------------------初始化座席状态----------------------------
/**
 * 心跳监测定时器
 */
var heartCheck = {
	    timeout: 30000,//60ms
	    timeoutObj: null,
	    reset: function(){
	        clearTimeout(this.timeoutObj);
	        this.start();
	    },
	    start: function(str){
	        this.timeoutObj = setInterval(function(){
	        	AjaxHeartBeatGet(str);
	        	if(websocket!=null){
	        		if(websocket.readyState!=1){
	        			connectWebsocket();
	        		}
	        		websocket.send("heartCheck");
	        	}
	           log(new Date()+"------heartCheck:"+str);
	        }, this.timeout)
	    }
	}

function AjaxHeartBeatGet(url){
	var result;
	$.ajax( {
		url : url,
		type : "GET",
		async : false,
		timeout : 1000,
		error : function(jqXHR, textStatus, errorThrown) {
		},
		success : function(data) {

			// showButtons(result.type);
		result = data;
	}

	});
     return result;
}


function connectWebsocket(){
	websocket = new WebSocket("ws://"+serverUrl+"/websocket/softphone/"+_sessionId);
    
 
   //连接发生错误的回调方法
     websocket.onerror = function(){
         log(" websocket.onerror :error");
     };

     //连接成功建立的回调方法
     websocket.onopen = function(event){
     	log(" websocket.onopen :open",event);
     	try{
			 AjaxHeartBeatGet(heartbeatUrl+"/"+place+"/"+loginCode);
			 log(new Date()+"------heartCheck:"+heartbeatUrl+"/"+place+"/"+loginCode);
	    	 heartCheck.start(heartbeatUrl+"/"+place+"/"+loginCode);
	    	 log("-----heartCheck:",heartCheck.timeoutObj);
	     }catch (e) {
			 log("-----heartCheck error:",e);
		 }
     }

     //接收到消息的回调方法
     websocket.onmessage = function(event){
     	log("websocket.onmessage is:",event.data);
     	echoRpcReturn(event.data);
     }

     //连接关闭的回调方法
     websocket.onclose = function(){
     	log(" websocket.onclose :close");
     }

     //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
     window.onbeforeunload = function(){
         websocket.close();
     }
}
var place;
var loginCode;


/**
 * StartContactCenterSession-初始化连接
 * 
 * @param place
 * @param loginCode
 * @param queue
 * @param channel
 * @return
 */
function init(_place, _loginCode, queue, channel) {
	if('WebSocket' in window){
		
	}else{
		alert("您的浏览器版本太低，请升级浏览器版本！");
		return;
	}
	place = _place;
	loginCode = _loginCode;
	//var json = "{" + "\"operationName\":\"StartContactCenterSession\""
	//		+ ",\"place\":\""+place + "\",\"loginCode\":\""+loginCode 
	//		+ "\",\"queue\":\"\"" + ",\"channels\":[\"chat\",\"voice\"]" + "}";
	
	var obj = new Object();
	obj.operationName = "StartContactCenterSession";
	obj.place = place;
	obj.loginCode = loginCode;
	obj.queue = "";
	if(channel!=null && channel != ''){
		obj.channels = eval('('+channel+')');
	}else{
		var mycars=new Array("voice");
		obj.channels = mycars;
	}
	var json=JSON.stringify(obj);

	var result = ajaxServlet("http://"+serverUrl+"/api/v1/me", json);
	if (result == null || result == "undefined") {
		alert("初始化失败！");
		return false;
	}
	var sessionId = result.sessionId;
	_sessionId = sessionId;
	var statusCode = result.statusCode;
	if (statusCode == 0) {
        showButtons(6);
        logout1();
	}else if(statusCode == 2) {//分机异常
		alert("话机异常，请检查话机！");
		return false;
	}
	
	if('WebSocket' in window){
		connectWebsocket();
	}
}



var websocket = null;
//关闭连接
function closeWebSocket(){
    websocket.close();
}

//发送消息
function send(){
    var message = document.getElementById('text').value;
    websocket.send(message);
}
//回复ack信息
function retrunAckMsg(refId){
	var message = "{\"EventName\":\"EventAck\",\"referenceId\":"+refId+"}";
	 websocket.send(message);
}

/**
 * echoRpcReturn cometd回调方法
 * 
 * @param msg
 * @return
 */
function echoRpcReturn(msg) {
	// alert(msg.data.msg);
	log("echoRpcReturn message is:"+new Date(),msg);
	var reseMsg;
	var eventName ='';
	if('WebSocket' in window){
		var logDiv = document.getElementById("responses");
		logDiv.innerHTML += new Date() + ":\n" + msg + "\n";
		logDiv.scrollTop = logDiv.scrollHeight;
		msg = eval('(' + msg + ')');
		if(msg.referenceId != undefined){
			log(msg.referenceId+"----");
			retrunAckMsg(msg.referenceId);
		}
		log("msg.data is:"+new Date(),msg.data);
		var reseMsg = msg;
		log("reseMsg is:",reseMsg);
	}
	
	
	if(reseMsg!=null&&reseMsg!=''&&reseMsg!='undefined'){
		if (reseMsg.data&&reseMsg.data.messageType == "DeviceStateChangeMessage") {
			handleAgentStatusChanged(reseMsg.data.devices);
		} else if (reseMsg.data&&reseMsg.data.messageType&&reseMsg.data.messageType == "CallStateChangeMessage") {
			CallStateChangeMessage(reseMsg.data);
		} else if (reseMsg.messageType&&reseMsg.messageType == "ChatStateChangeMessage") {
			chatStateChangeMessage(reseMsg.chat);
		} else if (reseMsg.messageType&&reseMsg.messageType == "MessageLogUpdated") {
			chatMessageReceive(reseMsg);
		} else if (reseMsg.messageType&&reseMsg.messageType == "ErrorMessage") {
			callMessageError(reseMsg);
		} 
	}
}

function log(msg, obj) {
	if(obj){
		console.log(msg, obj);
	}else{
		console.log(msg);
	}
}

/**
 * EndContactCenterSession结束session
 * 
 * @return
 */
function endContactCenterSession() {
	var json = "{" + "\"operationName\":\"EndContactCenterSession\""
			+ ",\"channel\":\"" + channel + "\"" + "}";
	url = "/api/v1/me/" + _sessionId;
	var result = ajaxServlet(url, json);
	return true;
}
/**
 * 座席登入
 * 
 * @param channel
 * @return
 */

function Online(channel) {
	//var json = "{" + "\"operationName\":\"Online\"" + ",\"channel\":\""
	//		+ channel + "\"" + "}";
	//var result = ajaxServlet(initChannelUrl + channel + "/" + _sessionId, json);
	var obj=new Object();
	obj.operationName="Online";
	obj.channel=channel;
	var json = JSON.stringify(obj);
	if (channel == 'voice') {
		var result = ajaxServlet(initChannelUrl + channel + "/" + _sessionId,
				json);
		if (result == null || result == "undefined") {
			alert("初始化失败！");
			return false;
		}
		var statusCode = result.statusCode;
		if (statusCode == 0) {
			showButtons(2);
		}else if(statusCode == 2) {//分机异常
			alert("话机异常，请检查话机！");
			return false;
		}
	} else {
		var result = ajaxServlet(initAllChannelUrl + _sessionId, json);
		if (result == null || result == "undefined") {
			alert("初始化失败！");
			return false;
		}
		var statusCode = result.statusCode;
		if (statusCode == 0) {
			showButtons(2);
		}else if(statusCode == 2) {//分机异常
			alert("话机异常，请检查话机！");
			return false;
		}
	}
	return true;
}

/**
 * 座席登出
 * 
 * @param mediaType(voice,
 *            mm)
 * @return
 */
function logout(channel) {
	//var json = "{" + "\"operationName\":\"LoggedOut\"" + ",\"channel\":\""
	//		+ channel + "\"" + "}";
	var obj=new Object();
	obj.operationName="LoggedOut";
	obj.channel=channel;
	var json = JSON.stringify(obj);
	if (channel == 'voice') {
		url = initChannelUrl + channel + "/" + _sessionId;
	} else {
		url = initAllChannelUrl + _sessionId;
	}
	ajaxServlet(url, json);
	return true;
}

/**
 * 根据channel置座席状态为Ready
 * 
 * @param channel
 * @return
 */
function ready(channel) {
	//var json = "{" + "\"operationName\":\"Ready\"" + ",\"channel\":\""
	//		+ channel + "\"" + "}";
	var obj=new Object();
	obj.operationName="Ready";
	obj.channel=channel;
	var json = JSON.stringify(obj);
	var result = '';
	if (channel == 'voice') {
		result = ajaxServlet(initChannelUrl + channel + "/" + _sessionId, json);
	} else {
		result = ajaxServlet(initAllChannelUrl + _sessionId, json);
	}
	return true;
}

/**
 * 置座席状态为NotReady
 * 
 * @param channel
 * @return
 */
function notReady(channel) {

	//var json = "{" + "\"operationName\":\"NotReady\""
	//		+ ",\"reasonCode\":\"meeting\"" + "}";
	//var result = '';
	var obj=new Object();
	obj.operationName="NotReady";
	obj.channel=channel;
	obj.reasonCode="meeting";
	var json = JSON.stringify(obj);
	if (channel == 'voice') {
		url = initChannelUrl + channel + "/" + _sessionId;
	} else {
		url = initAllChannelUrl + _sessionId;
	}
	ajaxServlet(url, json);
	return true;
}

/**
 * AuxWork 小休 AuxWork
 * 
 * @param channel
 * @return
 */
function auxWork(channel) {
	var json = "{" + "\"operationName\":\"AuxWork\"" + "}";
	url = initChannelUrl + channel + "/" + _sessionId;
	ajaxServlet(url, json);
	return true
}

/**
 * Offline 设置当前的座席为Offline(Logout)状态
 * 
 * @param channel
 * @return
 */
function offLine(channel) {
	//var json = "{" + "\"operationName\":\"Offline\"" + "}";
	var obj=new Object();
	obj.operationName="Offline";
	var json = JSON.stringify(obj);
	
	if (channel == 'voice') {
		url = initChannelUrl + channel + "/" + _sessionId;
	} else {
		url = initAllChannelUrl + _sessionId;
	}
	ajaxServlet(url, json);
	return true;
}

/**
 * afterCallWork事后处理
 * 
 * @param channel
 * @return
 */
function afterCallWork(channel) {
	var json = "{" + "\"operationName\":\"AfterCallWork\"" + "}";
	url = initChannelUrl + channel + "/" + _sessionId;
	ajaxServlet(url, json);
	return true
}
// ---------------------------------初始化座席状态 end----------------------------
// ---------------------------------外拨电话 start------------------------------
/**
 * 外拨电话
 * 
 * @param phoneNumber
 * @param params
 * @return
 */
function dialCall(phoneNumber, params) {
	//var json = "{" + "\"operationName\":\"Dial\""
	//		+ ",\"destination\":{\"phoneNumber\":\"" + phoneNumber + "\"}"
	//		+ ",\"userData\":" + params + "}";
	var obj=new Object();
	var obj1=new Object();
    var pn = "";
    if(phoneNumber.length==12){
        pn = phoneNumber.substring(1,phoneNumber.length);
    }else{
        pn = phoneNumber;
    }
    var reg = /^((1[3-8][0-9])\d{8})$/;
    if(reg.test(pn)){
        phoneNumber = "9"+ phoneNumber;
    }else{
        phoneNumber = "6"+ phoneNumber;
    }
	obj1.phoneNumber=phoneNumber;
	obj.operationName="Dial";
	obj.destination=obj1;
	obj.userData=eval('('+params+')');
	var json = JSON.stringify(obj);
	url = "http://"+serverUrl+"/api/v1/me/devices/" + _sessionId + "/calls";
	ajaxServlet(url, json);

}

/**
 * 接听电话
 * 
 * @param connId
 * @param params
 *            可选参数
 * @return
 */
function answerCall(connId) {
	//var json = "{" + "\"operationName\":\"Answer\"" + ",\"connId\":\"" + connId
	//		+ "\"" + "}";
	var json=calljsonToString(connId,"Answer");
	url = callUrl + _sessionId
	ajaxServlet(url, json);
}

/**
 * 挂断电话
 * 
 * @param connId
 * @param params
 *            可选参数
 * @return
 */
function hangup(connId) {
	//var json = "{" + "\"operationName\":\"Hangup\"" + ",\"connId\":\"" + connId
	//		+ "\"" + "}";
	var json;
		
		json=calljsonToString(connId,"Hangup");
		url = callUrl + _sessionId
	var result = ajaxServlet(url, json);
	return result;
}

/**
 * 保持电话
 * 
 * @param connId
 * @param params
 *            可选参数
 * @return
 */
function holdCall(connId) {
	//var json = "{" + "\"operationName\":\"Hold\"" + ",\"connId\":\"" + connId
	//		+ "\"" + "}";
	var json;
	  json=calljsonToString(connId,"Hold");
	url = callUrl + _sessionId;
	var result = ajaxServlet(url, json);
	return result;
}

/**
 * 保持取回
 * 
 * @param connId
 * @param params
 *            可选参数
 * @return
 */
function retrieveCall(connId) {
	//var json = "{" + "\"operationName\":\"Retrieve\"" + ",\"connId\":\""
	//		+ connId + "\"" + "}";
	var json;
	json=calljsonToString(connId,"Retrieve");
	url = callUrl + _sessionId;
	var result = ajaxServlet(url, json);
	return result;
}

/**
 * 拒接电话
 * 
 * @param interactionId
 * @return
 */
function rejectCall(connId) {

	//var json = "{" + "\"operationName\":\"Reject\"" + ",\"connId\":\"" + connId
	//		+ "\"" + "}";
	var json=calljsonToString(connId,"Reject");
	url = callUrl + _sessionId;
	var result = ajaxServlet(url, json);
	return result;
}

/**
 * SendDTMF发送DTMF
 * 
 * @return
 */
function SendDtmf(digits) {
	var json = "{" + "\"operationName\":\"SendDtmf\"" + ",\"digits\":\""
			+ digits + "\"" + "}";
	var result = ajaxServlet(callUrl + _sessionId, json);
	return result;
}

/**
 * muteCall静音当前的呼叫，当静音是on时，座席可以听到其他Partcipant的语音， 但是其他Partcipant听不到座席的说话
 * 
 * @param params
 *            可选参数
 * @return
 */
function muteCALL(connId) {
	//var json = "{" + "\"operationName\":\"Mutecall\"" + ",\"connid\":\""
	//		+ connId + "\"" + "}";
	var json=calljsonToString(connId,"Mutecall");
	var result = ajaxServlet(callUrl + connId, json);
	return result;
}

/**
 * UnMutecall取消静音
 * 
 */
function unmuteCall(connid) {
	var json = "{" + "\"operationName\":\"UnMutecall\"" + ",\"digits\":\""
			+ digits + "\"" + "}";
	var result = ajaxServlet(callUrl + connid, json);
	return result;
}
// ---------------------------------拨打电话 end----------------------------

//----------------------------------工具处理-------------------------------------------
/**
 * formatArrayToString 将数组转化为字符串，目前没用
 * @param dataArray
 * @return
 */
function formatArrayToString(dataArray) {
	var str = "";
	for ( var index = 0; index < dataArray.length; index++) {
		str += dataArray[index] + "##";
	}
	return str;
}

/**
 * AjaxServlet 处理softphone的相应请求
 * 
 * @param url
 *            接口地址
 * @param prams
 *            相应的json参数
 * @return
 */
function ajaxServlet(url, prams) {
	log("ajaxServlet the url is:"+url+",and the prams is:",prams);
	var result;
	var statusCode = 1;
	$.ajax( {
		url : url,
		type : "POST",
		data : prams,
		dataType : "json",
		contentType : "application/json",
		async : false,
		timeout : 1000,
		error : function() {
		},
		success : function(data) {

		result = data;
	}

	});
	return result;
}

/**
 * calljsonToString 拨打电话所需要的参数
 * @param connId
 * @param operationName
 * @return
 */
function calljsonToString(connId,operationName){
	var obj=new Object();
	obj.operationName=operationName;
	obj.connId=connId;
	var json = JSON.stringify(obj);
	return json;
}
function inComingCall(result,type) {
    log("inComingCall start");
    var number = result.phoneNumber;
    var connId = result.call.connId;
    var userData = result.call.userData;
    if(userData!=null){
        place = userData.RTargetPlaceSelected;
    }else{
        place = result.call.dnis;
    }
    var sessionId = _sessionId;

    $.ajax( {
        url : basePath+"api/inComingCall.do",
        type : "POST",
        data : {number:number,connId:connId,place:place,sessionId:sessionId,type:type},
        dataType : "String",
        async : false,
        timeout : 1000,
        error : function() {
        },
        success : function(data) {
            log(data);
        }
    })
    log("inComingCall end");
}

//----------------------------------工具处理-end-----------------------------------------
